import tkinter as tk
from tkinter import LabelFrame, W, E
from tkinter import ttk
from tkinter import messagebox

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

import bookCharge
import bookCheckout
import bookInfo
import bookRecommend
import bookReturn


class LibraryManagementSystem:

    def __init__(self, window):
        # Initializations
        self.wind = window
        self.wind.title("Library Manage System")
        self.wind.geometry("1000x500")

        # Welcome Words
        label = tk.Label(window, text="Here you can find books information")
        label.grid(row=0, column=0)

        # Button list book messages
        list_button = tk.Button(window, text="list books", command=self.book_message,
                                width=15, height=2)
        list_button.place(x=800, y=100)

        # Creating a Frame Container
        frame = LabelFrame(self.wind, text="Book check out and return")
        frame.grid(row=5, column=0, columnspan=2, pady=20)

        # user id input
        tk.Label(frame, text="user_id: ", width=15, height=3).grid(row=6, column=0)
        self.user_id = tk.Entry(frame)
        self.user_id.focus()
        self.user_id.grid(row=6, column=1)

        # book id input
        tk.Label(frame, text="book_id: ", width=15, height=3).grid(row=7, column=0)
        self.book_id = tk.Entry(frame)
        self.book_id.focus()
        self.book_id.grid(row=7, column=1)

        # Button check out books
        check_out_button = tk.Button(frame, text="check out",
                                     width=8, height=1, command=self.check_out_books)
        check_out_button.grid(row=8, column=0, sticky=W)

        # Button return books
        return_button = tk.Button(frame, text="return",
                                  width=8, height=1, command=self.return_books)
        return_button.grid(row=8, column=1, sticky=E)

        # Button recommend books
        recommend_button = tk.Button(window, text="recommend books",
                                     width=15, height=2, command=self.recommend_books)
        recommend_button.place(x=800, y=220)

        # Button overdue books
        overdue_button = tk.Button(window, text="overdue books",
                                   width=15, height=2, command=self.overdue_books)
        overdue_button.place(x=800, y=340)

        # fill the rows
        self.book_message()

    # book check out function
    def check_out_books(self):
        book_id = self.book_id.get()
        member_id = self.user_id.get()
        if self.validation_member_id():
            if self.validation_book_id():
                if bookCheckout.book_check_out(member_id, book_id):
                    tk.messagebox.showinfo(title="Congratulations",
                                           message="You have borrowed the book successfully!")
                else:
                    tk.messagebox.askretrycancel(title="Sorry",
                                                 message="The book can not be borrowed or you hold any overdue book!")
            else:
                tk.messagebox.askretrycancel(title="Sorry",
                                             message="The book id you input is null or it is not valid!")
        else:
            tk.messagebox.askretrycancel(title="Sorry",
                                         message="The member id you input is null or it is not valid!")
        self.book_message()

    # return book function
    def return_books(self):
        book_id = self.book_id.get()
        if self.validation_book_id():
            if bookReturn.book_return(book_id) == "2":
                tk.messagebox.showinfo(title="Congratulations",
                                       message="You have returned the book successfully!")

            elif bookReturn.book_return(book_id) == "0":
                tk.messagebox.showerror(title="Sorry",
                                        message="You can not return the book because the book has been returned!")

            else:
                tk.messagebox.showwarning(title="Sorry",
                                          message="You return the book late! You should return the book on time!")
        else:
            tk.messagebox.askretrycancel(title="Sorry",
                                         message="The book id you input is null or it is not valid!")
        self.book_message()

    # recommend books function
    def recommend_books(self):
        # Table
        cols = ["id", "genre", "title", "author", "loan_periods", "purchase_date", "member"]
        self.tree = ttk.Treeview(height=10, columns=cols, show="headings")
        self.tree.grid(row=4, column=0, columnspan=2)
        for x in cols:
            self.tree.column(x, width=110)
            self.tree.heading(column=x, text=x, anchor="center")
        # cleaning Table
        records = self.tree.get_children()
        for element in records:
            self.tree.delete(element)
        # getting data
        book_info = bookRecommend.book_recommend()
        # filling data
        i = 0
        for row in book_info:
            self.tree.insert("", i, values=(row[0], row[1], row[2], row[3], row[4], row[5], row[6]))
            i += 1

    # overdue books function
    def overdue_books(self):
        # Table
        cols = ["id", "member", "fines"]
        self.tree = ttk.Treeview(height=10, columns=cols, show="headings")
        self.tree.grid(row=5, column=1, columnspan=2)
        for x in cols:
            self.tree.column(x, width=70)
            self.tree.heading(column=x, text=x, anchor="center")
        # cleaning Table
        records = self.tree.get_children()
        for element in records:
            self.tree.delete(element)
        # getting data
        overdue_books = bookCharge.book_overdue()
        # filling data
        i = 0
        for row in overdue_books:
            self.tree.insert("", i, values=(row[0], row[1], row[2]))
            i += 1

    # book list function
    def book_message(self):
        # Table
        cols = ["id", "genre", "title", "author", "loan_periods", "purchase_date", "member"]
        self.tree = ttk.Treeview(height=10, columns=cols, show="headings")
        self.tree.grid(row=4, column=0, columnspan=2)
        for x in cols:
            self.tree.column(x, width=110)
            self.tree.heading(column=x, text=x, anchor="center")
        # cleaning Table
        records = self.tree.get_children()
        for element in records:
            self.tree.delete(element)
        # getting data
        book_info = bookInfo.book_info()
        # filling data
        i = 0
        for row in book_info:
            self.tree.insert("", i, values=(row[0], row[1], row[2], row[3], row[4], row[5], row[6]))
            i += 1

    # validate the book_id
    def validation_book_id(self):
        if self.book_id.get().isdigit():
            book_id_list = bookInfo.book_id()
            if self.book_id.get() in book_id_list:
                return True
            else:
                return False
        else:
            return False

    # validate the member_id
    def validation_member_id(self):
        if len(self.user_id.get()) == 4:
            if self.user_id.get().isdigit():
                return False
            else:
                return True
        else:
            return False


if __name__ == "__main__":
    # run this window
    window = tk.Tk()
    application = LibraryManagementSystem(window)
    window.mainloop()
